/*
 * @lc app=leetcode.cn id=637 lang=cpp
 *
 * [637] 二叉树的层平均值
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    vector<double> averageOfLevels(TreeNode *root) {
        vector<double> ans;           // 保存结果，即每层的平均数
        queue<TreeNode *> treeQueue;  // 保存节点

        if (root == nullptr) return ans;

        // BFS
        treeQueue.push(root);
        while (!treeQueue.empty()) {
            int length = treeQueue.size();      // 每一层的节点数
            double sum = 0;                     // 每一层的节点值总和
            for (int i = 0; i < length; i++) {
                TreeNode *node = treeQueue.front();
                treeQueue.pop();
                sum += node->val;
                if (node->left != nullptr) treeQueue.push(node->left);
                if (node->right != nullptr) treeQueue.push(node->right);
            }
            ans.push_back(sum / length);
        }

        return ans;
    }
};
// @lc code=end
